/* ==================================================================   
 * Created [2009-4-27 下午11:32:55] by Jon.King 
 * ==================================================================  
 * TSS 
 * ================================================================== 
 * mailTo:jinpujun@hotmail.com
 * Copyright (c) Jon.King, 2009-2012 
 * ================================================================== 
 */

package com.jinhe.tss.portal.sso;

import java.io.IOException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.log4j.Logger;

import com.jinhe.tss.core.Global;
import com.jinhe.tss.core.sso.Environment;
import com.jinhe.tss.core.sso.ILoginCustomizer;
import com.jinhe.tss.core.sso.IPWDOperator;
import com.jinhe.tss.core.sso.SSOConstants;
import com.jinhe.tss.core.sso.appserver.AppServer;
import com.jinhe.tss.core.sso.context.Context;
import com.jinhe.tss.um.service.ILoginService;

/** 
 * <p> OAPasswordCustomizer.java </p> 
 * 对OA用户密码的自定义操作。<br>
 * 在PMS登陆时（主要通过PMS搭建的门户网站登陆），如果能执行本对象的自定义操作，说明用户已经登陆成功。<br>
 * 取到用户登陆时输入的密码，和登陆时候生成的OperatorDTO对象，再通过OperatorDTO对象里的otherAppUserId取到用户对应的OA组用户，<br>
 * 比较两者密码，如果相等则不做处理；否则，请求UMS中重新设置密码的servlet来重新处理密码同步问题。
 * 
 */
public class OAPasswordCustomizer implements ILoginCustomizer {
    
    protected Logger log = Logger.getLogger(this.getClass());
    
    private AppServer appServer;
    private ILoginService loginService;
    
    public OAPasswordCustomizer() {
        appServer = Context.getApplicationContext().getAppServer("UMS");
        loginService = (ILoginService) Global.getContext().getBean("LoginService");
    }

    public void execute() {
        try{
            String password  = Context.getRequestContext().getValueFromHeaderOrParameter(SSOConstants.USER_PASSWORD);
            if(password == null)
                return;
            
//1、以下方式取主用户的对应用户方法是不对的，主用户组的用户可能对应多个应用的用户，所以用otherAppUserId取是错误的     
//            IOperator operator = Context.getIdentityCard().getOperator();
//            Long oaUserId = Long.valueOf((String) operator.getAttribute("otherAppUserId")); 
//            IPasswordOperator oaUser = loginService.getOperatorDTOByID(oaUserId);
//2、正确的做法应该如下：            
            Long operatorId = Environment.getOperatorId();
            IPWDOperator oaUser = loginService.translateUser(operatorId, "OA");
            
            if (oaUser.getPassword().equals(password))
                return;
            
            HttpClient httpClient = new HttpClient(); //构造HttpClient的实例
            
            PostMethod postMethod = new PostMethod(appServer.getBaseURL() + "/resetPassword.in");
            // 填入各个表单域的值
            NameValuePair[] params = { new NameValuePair("userId", operatorId.toString()), 
                                       new NameValuePair("password", password), 
                                       new NameValuePair("newPassword", password) };
            // 将表单的值放入postMethod中
            postMethod.setRequestBody(params);
            // 执行postMethod
            try {
                int statusCode = httpClient.executeMethod(postMethod);
                if(statusCode == HttpStatus.SC_OK){
                    // 读取内容
                    byte[] responseBody = postMethod.getResponseBody();
                    log.info(new String(responseBody));
                }
            } catch (HttpException e) {
                log.error("执行请求修改密码的Servlet时，登陆servlet的连接地址可能有误！", e);
            } catch (IOException e) {
                log.error("执行请求修改密码的Servlet时，出现IO异常！", e);
            }finally{
                postMethod.releaseConnection();
            }
        } catch (Exception e) {
            log.error("PMS中执行OAPasswordCustomizer自定义操作时候失败！", e);
        } 
    }
}

